package cn.org.eshow.webapp.action;

import cn.org.eshow.bean.query.OrderItemQuery;
import cn.org.eshow.bean.query.ProductOrderQuery;
import cn.org.eshow.common.page.Page;
import cn.org.eshow.model.*;
import cn.org.eshow.service.*;
import cn.org.eshow.util.JacksonUtil;
import cn.org.eshow.util.OrderUtil;
import cn.org.eshow.webapp.action.response.OrderItemResponse;
import cn.org.eshow.webapp.action.response.ProductOrderResponse;
import cn.org.eshow.webapp.util.RenderUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.AllowedMethods;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品订单 API接口
 */
@AllowedMethods({"mine", "count", "save", "cancelOrder", "conform","view"})
public class ProductOrderAction extends ApiBaseAction<ProductOrder> {

    private static final long serialVersionUID = 1L;

    @Autowired
    private AddressManager addressManager;
    @Autowired
    private ProductOrderManager productOrderManager;
    @Autowired
    private CartManager cartManager;
    @Autowired
    private ProductItemManager productItemManager;
    @Autowired
    private UserCouponManager userCouponManager;
    @Autowired
    private OrderItemManager orderItemManager;
    @Autowired
    private OrderStepManager orderStepManager;

    private ProductOrder productOrder = new ProductOrder();
    private List<ProductOrder> productOrders = new ArrayList<ProductOrder>();
    private ProductOrderQuery query = new ProductOrderQuery(Boolean.TRUE);

    private String cartIds; //订单提交关联的购物车ID
    private Integer addressId; //收货地址ID
    private Integer productSize = 1;//商品数量
    private Integer productItemId;//详细商品ID


    /**
     * 获取博文信息
     */
    public void view() {
        ProductOrder old = productOrderManager.get(id);
        if (old == null) {
            RenderUtil.failure("非法参数");
            return;
        }
        ProductOrderResponse response = new ProductOrderResponse(old);
        RenderUtil.success("获取成功", "productOrder", response);
    }

    /**
     * 我的订单列表
     * query.state=100 : 进行中
     * query.state=1 : 已完成
     * query.refundStates= 1,2,3 : 售后
     */
    public void mine() {
        User user = accessTokenManager.isValid(accessToken);
        if (user == null) {
            RenderUtil.expires();//用户信息过期
            return;
        }
        query.setUserId(user.getId());
        Page<ProductOrder> page = productOrderManager.search(query);
        productOrders = page.getDataList();
        if (productOrders.isEmpty()) {
            RenderUtil.noData();
            return;
        }
        List<ProductOrderResponse> responses = new ArrayList<ProductOrderResponse>();
        for (ProductOrder obj : productOrders) {
//            responses.add(new ProductOrderResponse(obj));
            ProductOrderResponse productOrderResponse = new ProductOrderResponse(obj);
            List<OrderItemResponse> orderItemResponses = new ArrayList<OrderItemResponse>();
            List<OrderItem> orderItems = orderItemManager.list(new OrderItemQuery(obj.getId()));
            for (OrderItem orderItem : orderItems) {
                orderItemResponses.add(new OrderItemResponse(orderItem));
            }
            productOrderResponse.setOrderItems(orderItemResponses);
            responses.add(productOrderResponse);
        }
        RenderUtil.page("获取成功", "productOrders", page, responses);
    }


    /**
     * 提交商品订单(cartIds走购物车流程、productItemId productSize立即购买流程)
     *
     * @return
     */
    public void save() {

        if (addressId == null) {
            RenderUtil.failure("请传入完整参数");
            return;
        }
        User user = accessTokenManager.isValid(accessToken);
        if (user == null) {
            RenderUtil.expires();//用户信息过期
            return;
        }
        Address address = addressManager.get(addressId);
        if (address == null) {
            RenderUtil.failure("用户地址不存在");
            return;
        }
        if (!address.getUser().getId().equals(user.getId())) {
            RenderUtil.failure("非当前用户收货地址");
            return;
        }
        if (productOrder.getUserCoupon() != null && productOrder.getUserCoupon().getId() != null) {//是否使用红包
            UserCoupon userCoupon = userCouponManager.get(productOrder.getUserCoupon().getId());
            Coupon coupon = userCoupon.getCoupon();
            if (coupon.getState() != 2) {//只有优惠券模版状态为2时,表示使用中。方能使用优惠券
                RenderUtil.failure("暂时无法使用该红包");
                return;
            }
            productOrder.setCoupon(userCoupon.getCoupon().getMoney());
        }

        if (StringUtils.isEmpty(cartIds) && productItemId == null) {
            RenderUtil.failure("请传入完整参数");
            return;
        }
        if (!StringUtils.isEmpty(cartIds)) {//cartIds走购物车流程
            String[] cartIdArray = cartIds.split(",");//购物车ID数组
            List<Cart> carts = new ArrayList<Cart>();//购物车对象列表
            for (String cartId : cartIdArray) { //循环购物车ID数据
                Cart cart = cartManager.get(Integer.valueOf(cartId));
                if (cart == null) {
                    continue;
                } else {
                    if (!cart.getUser().getId().equals(user.getId()))
                        continue;//如果购物车商品不是当前用户则不处理
                    carts.add(cart);
                }
            }
            if (carts.isEmpty()) {
                RenderUtil.failure("购物车内暂无商品");
                return;
            }

            productOrder.setNo(OrderUtil.getOrderNo());
            productOrder = productOrderManager.save(productOrder);
            productOrder = productOrderManager.save(productOrder, user, carts, address);//productOrder需要提前生成
            for (Cart cart : carts) {
                cartManager.remove(cart);
            }

            RenderUtil.success(productOrder.getId().toString());
            return;
        }
        if (productItemId != null) {//productId productSize立即购买流程
            ProductItem productItem = productItemManager.get(productItemId);
            if (productItem == null) {
                RenderUtil.failure("该详细商品不存在");
                return;
            }
            productOrder = productOrderManager.save(productOrder, user, productItemId.toString(), productSize.toString(), address);
            RenderUtil.success(productOrder.getId().toString());
            return;
        }
        RenderUtil.failure("添加失败");
        return;
    }


    /**
     * 气泡:我的订单数量
     */
    public void count() {
        User user = accessTokenManager.isValid(accessToken);
        if (user == null) {
            RenderUtil.expires();//用户信息过期
            return;
        }

        Integer inProgress = productOrderManager.count(new ProductOrderQuery(user.getId(), 100));//进行中
        Integer aftermarket = productOrderManager.count(new ProductOrderQuery(user.getId(), "1,2,3"));//售后

        Map<String, String> map = new HashMap<String, String>();
        map.put("inProgress", JacksonUtil.toJson(inProgress));
        map.put("aftermarket", JacksonUtil.toJson(aftermarket));
        RenderUtil.result(1, "获取成功", map);
    }

    /**
     * 取消待支付、已付款订单
     */
    public void cancelOrder() {
        if (id == null) {
            RenderUtil.failure("缺少参数");
            return;
        }
        ProductOrder old = productOrderManager.get(id);
        if (old.getState() != 0 && old.getState() != 2) {
            RenderUtil.failure("只有待支付、已付款订单能取消订单");
            return;
        }
        if (old.getState() == 0) {
            old=productOrderManager.cancel(old);
            RenderUtil.success("取消成功");
            return;
        }
        if (old.getState() == 2) {
            old=productOrderManager.executeRefund(old, old.getPay());
            RenderUtil.success("取消成功");
            return;
        }
        RenderUtil.failure("取消失败");
    }

    /**
     * 验收
     */
    public void conform() {
        if (id == null) {
            RenderUtil.failure("缺少参数");
            return;
        }
        ProductOrder old = productOrderManager.get(id);
        if (old.getHandleState() != 2) {
            RenderUtil.failure("当前订单不是待验收状态");
            return;
        }
        old= productOrderManager.conform(old);
        RenderUtil.success("验收成功");
    }

    public ProductOrder getProductOrder() {
        return productOrder;
    }

    public void setProductOrder(ProductOrder productOrder) {
        this.productOrder = productOrder;
    }

    public List<ProductOrder> getProductOrders() {
        return productOrders;
    }

    public void setProductOrders(List<ProductOrder> productOrders) {
        this.productOrders = productOrders;
    }

    public ProductOrderQuery getQuery() {
        return query;
    }

    public void setQuery(ProductOrderQuery query) {
        this.query = query;
    }

    public String getCartIds() {
        return cartIds;
    }

    public void setCartIds(String cartIds) {
        this.cartIds = cartIds;
    }

    public Integer getAddressId() {
        return addressId;
    }

    public void setAddressId(Integer addressId) {
        this.addressId = addressId;
    }

    public Integer getProductSize() {
        return productSize;
    }

    public void setProductSize(Integer productSize) {
        this.productSize = productSize;
    }

    public Integer getProductItemId() {
        return productItemId;
    }

    public void setProductItemId(Integer productItemId) {
        this.productItemId = productItemId;
    }
}